<template>
  <div class="login">
    <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form">
      <h3 class="title">欢迎登录</h3>
      <el-form-item prop="username">
        <el-input
            v-model="loginForm.username"
            type="text"
            auto-complete="off"
            placeholder="用户名"
        >
          <i slot="prefix" class="el-icon-user" />
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
            v-model="loginForm.password"
            type="password"
            auto-complete="off"
            placeholder="密码"
            @keyup.enter.native="handleLogin"
        >
          <i slot="prefix" class="el-icon-lock" />
        </el-input>
      </el-form-item>
      <el-button :loading="loading" size="medium" type="warning" style="width:45%;" @click.native.prevent="handleLogin">登录</el-button>
      <el-button size="medium" type="warning" style="width:45%;margin-left: 10%" @click.native.prevent="$router.push('/register')">注册</el-button>
    </el-form>
  </div>
</template>

<script>
import { recordLog } from '@/api/recordLog'

export default {
  name: 'Login',
  data() {
    return {
      loginForm: {
        username: '',
        password: ''
      },
      loginRules: {
        username: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
        password: [{ required: true, message: '密码不能为空', trigger: 'blur' }]
      },
      loading: false
    }
  },
  methods: {
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          this.$store.dispatch('user/login', this.loginForm).then(() => {
            this.$store.dispatch('user/getInfo')
            this.$router.push({ path: '/' })
            this.loading = false
            recordLog({ username: this.loginForm.username, operate: '登录系统' })
          }).catch(() => {
            this.loading = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<style scoped>
.login {
  min-height: 100%;
  width: 100%;
  background-image: url("../assets/login_back.jpg");
  background-size: cover;
  display: -webkit-flex;
  display: flex;
  justify-content: center;
  align-items: center;
}
.login-form {
  border-radius: 6px;
  background: #fff;
  width: 350px;
  padding: 25px 25px 25px 25px;
}
.title {
  margin: 0 auto 30px auto;
  text-align: center;
  color: #707070;
}
</style>
